package com.micro.ai.agents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.agents.entity.AgentConfig;
import com.micro.ai.agents.mapper.AgentConfigMapper;
import com.micro.ai.agents.service.AgentConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 智能体配置服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class AgentConfigServiceImpl extends ServiceImpl<AgentConfigMapper, AgentConfig> implements AgentConfigService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgentConfig create(AgentConfig config) {
        if (config == null) {
            throw new BusinessException("A0000", "配置信息不能为空");
        }
        
        if (!StringUtils.hasText(config.getAgentId())) {
            throw new BusinessException("A0000", "智能体ID不能为空");
        }
        
        if (!StringUtils.hasText(config.getConfigKey())) {
            throw new BusinessException("A0000", "配置键不能为空");
        }
        
        // 检查配置键是否已存在
        LambdaQueryWrapper<AgentConfig> query = new LambdaQueryWrapper<>();
        query.eq(AgentConfig::getAgentId, config.getAgentId())
             .eq(AgentConfig::getConfigKey, config.getConfigKey());
        
        AgentConfig existing = this.getOne(query);
        if (existing != null) {
            throw new BusinessException("A0001", "配置键已存在: " + config.getConfigKey());
        }
        
        if (config.getConfigType() == null) {
            config.setConfigType("string");
        }
        if (config.getIsPublic() == null) {
            config.setIsPublic(false);
        }
        
        LocalDateTime now = LocalDateTime.now();
        config.setCreatedAt(now);
        config.setUpdatedAt(now);
        
        boolean success = this.save(config);
        if (!success) {
            throw new BusinessException("A0003", "保存配置失败");
        }
        
        log.info("创建智能体配置成功: configId={}, agentId={}, key={}", 
                config.getId(), config.getAgentId(), config.getConfigKey());
        return config;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgentConfig update(String id, AgentConfig config) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "配置ID不能为空");
        }
        if (config == null) {
            throw new BusinessException("A0000", "配置信息不能为空");
        }
        
        AgentConfig existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("A0002", "配置不存在: " + id);
        }
        
        config.setId(id);
        config.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(config);
        if (!success) {
            throw new BusinessException("A0003", "更新配置失败");
        }
        
        log.info("更新智能体配置成功: configId={}", id);
        return config;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "配置ID不能为空");
        }
        
        AgentConfig config = this.getById(id);
        if (config == null) {
            throw new BusinessException("A0002", "配置不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("A0003", "删除配置失败");
        }
        
        log.info("删除智能体配置成功: configId={}, key={}", id, config.getConfigKey());
    }

    @Override
    public List<AgentConfig> listByAgentId(String agentId) {
        LambdaQueryWrapper<AgentConfig> query = new LambdaQueryWrapper<>();
        query.eq(AgentConfig::getAgentId, agentId)
             .orderByAsc(AgentConfig::getConfigKey);
        
        return this.list(query);
    }

    @Override
    public Page<AgentConfig> pageQuery(int pageNum, int pageSize, String tenantId, String agentId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<AgentConfig> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AgentConfig> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(AgentConfig::getTenantId, tenantId);
        }
        if (StringUtils.hasText(agentId)) {
            query.eq(AgentConfig::getAgentId, agentId);
        }
        
        query.orderByDesc(AgentConfig::getCreatedAt);
        
        return this.page(page, query);
    }
}

